<?php
/**
 * Created by PhpStorm
 * User: y.
 * Email: 707186758@qq.com
 * Date: 2023/6/16
 * Time: 16:10
 */

namespace app\common\service;


class TenIM extends Base
{
    
    
    /**
     * 获取用户秘钥
     */
    public function generateSign($identifier): string
    {
        $api = new TLSSigAPIv2($this->config['tencentIMSdkAppId'], $this->config['tencentIMSdkAppkey']);
        
        return $api->genUserSig($identifier, config('my.token_expire_in'));
    }
    
    /**
     * 导入单个账号
     */
    public function importAccount($userInfo)
    {
        $params = [
            'Identifier' => $userInfo['membe_id'],
            'Nick' => $userInfo['username'],
            'FaceUrl' => formatImgUrl($userInfo['pic']),
        ];
        return $this->im->send('im_open_login_svc', 'account_import', $params);
    }
    
    /*
     *  查询账号是否存在
     */
    public function checkAccount($uid)
    {
        $params = [
            'CheckItem' => []
        ];
        $params['CheckItem'][]["UserID"] = $uid;
        return $this->im->send('im_open_login_svc', 'account_check', $params);
    }
    
    /**
     * 获取用户在线状态
     */
    public function getUserOnline($userArr)
    {
        $params = [
            'To_Account' => $userArr
        ];
        return $this->im->send('openim', 'query_online_status', $params);
    }
    
    /**
     * 修改IM用户信息
     */
    public function editUserInfo($userInfo)
    {
        $params = [
            'From_Account' => $userInfo['uid'],
            'ProfileItem' => [
            ],
        ];
        
        if (isset($userInfo['username']) && $userInfo['username']) {
            $params['ProfileItem'][] = ['Tag' => 'Tag_Profile_IM_Nick', 'Value' => $userInfo['username']];
        }
        
        if (isset($userInfo['pic']) && $userInfo['pic']) {
            $params['ProfileItem'][] = ['Tag' => 'Tag_Profile_IM_Image', 'Value' => formatImgUrl($userInfo['pic'])];
        }
        
        if (isset($userInfo['signature_des']) && $userInfo['signature_des']) {
            //selfSignature
            $params['ProfileItem'][] = ['Tag' => 'Tag_Profile_IM_SelfSignature', 'Value' => $userInfo['signature_des']];
        }
        
        if (isset($userInfo['sex']) && $userInfo['sex']) {
            $sex = "Gender_Type_Unknown";
            if($userInfo['sex'] == 1){
                $sex = "Gender_Type_Female";
            }elseif ($userInfo['sex'] == 2) {
                // code...
                $sex = "Gender_Type_Male";
            }
            
             $params['ProfileItem'][] = ['Tag' => 'Tag_Profile_IM_Gender', 'Value' => $sex];
        }
        
        // if (isset($userInfo['word_price']) && $userInfo['word_price']) {
           
            // $params['ProfileItem'][] = ['Tag' => 'Tag_Profile_Custom_Birthday', 'Value' => "20190419"];
        // }
        
        // if (isset($userInfo['word_count']) && $userInfo['word_count']) {
           
        //     $params['ProfileItem'][] = ['Tag' => 'Tag_Profile_IM_Location', 'Value' => $userInfo["word_count"]];
        // }
        
        return $this->im->send('profile', 'portrait_set', $params);
    }
    
    /**
     * 修改IM用户等级
     */
    public function editUserInfo_level($uid,$level)
    {
        //用户级别   Tag_Profile_IM_Level
        //写手级别   Tag_Profile_IM_Language    
        //橱窗展示    Tag_Profile_IM_Location
        $params = [
            'From_Account' => $uid,
            'ProfileItem' => [
            ],
        ];
        
     
        $params['ProfileItem'][] = ['Tag' => 'Tag_Profile_IM_Level', 'Value' => $level];
       
        return $this->im->send('profile', 'portrait_set', $params);
    }
    
    
    /**
     * 查看IM用户信息
     */
    public function getIMUserInfo($uid)
    {
        $params = [
            "To_Account" => $uid,
            "TagList" =>
                [
                    "Tag_Profile_IM_Nick",
                    "Tag_Profile_IM_Image"
                ]
        ];
        return $this->im->send('profile', 'portrait_get', $params);
    }
    
    /**
     * 查询用户未读消息数
     */
    public function getMsgNum($uid)
    {
        $params = [
            "To_Account" => $uid
        ];
        return $this->im->send('openim', 'get_c2c_unread_msg_num', $params);
    }
    
    
    /**
     * 发送系统消息
     */
    public function sendSystemMsg($uid, $msg)
    {
        
    
        $params = [
            "To_Account" => $uid,
            "MsgRandom" => rand(),
            "MsgBody" => [[
                "MsgType" => "TIMTextElem",
                "MsgContent" => [
                    // "Text" => '【' . (config('base_config.sys_msg_prefix') ?? '系统消息') . '】' . $msg
                    "Text" =>  $msg
                ]
            ]]
        ];
        return $this->im->send('openim', 'sendmsg', $params);
    }
    
    //发送用户消息
    public function sendUserMsg($uid, $touid,$msg){
  
        if($touid == "writermsg"){
               
            //写手消息
            db("writer_apply")->where(["uid"=>$uid])->update(["is_new"=>1]);
            
            db("membe")->where(["membe_id"=>$uid])->update(["xt_new"=>1]);
   
            //写手消息
            $this->ts($uid,"你有新的系统消息",$msg);
        }else if($touid == "administrator" || $touid == "neworder"){
            //订单消息
            $this->ts($uid,"你有新的系统消息",$msg);
        }else if($touid == "hudongmsg"){
            //互动消息
            $this->ts($uid,"你有新的互动消息",$msg);
        }else{
            //其他消息
            $this->ts($uid,"你有新的订单消息",$msg);
        }
  
         $params = [
            "SyncOtherMachine"=>2,
            "From_Account"=>$touid,
            "To_Account" => $uid,
            "MsgRandom" => rand(),
            "MsgBody" => [[
                "MsgType" => "TIMTextElem",
                "MsgContent" => [
                    "Text" =>  $msg
                ]
            ]]
        ];
    
        return $this->im->send('openim', 'sendmsg', $params);
    }
    
    
     //发送用户消息
    public function sendUserMsg2($uid, $touid,$msg,$tid){

   
        if($touid == "writermsg"){
               
            //写手消息
            db("writer_apply")->where("uid","in",implode(",",$uid))->update(["is_new"=>1]);
            
            //写手消息
            if(!empty($tid)){
                $this->ts1($tid,"你有新的系统消息",$msg,$tid);
            }
          
        }else if($touid == "administrator" || $touid == "neworder"){
            //订单消息
            
            if(!empty($tid)){
              $this->ts1($tid,"你有新的订单消息",$msg,$tid);
            }
        }else if($touid == "hudongmsg"){
            //互动消息
            if(!empty($tid)){
              $this->ts1($tid,"你有新的互动消息",$msg,$tid);
            }
        }else{
            //其他消息
             if(!empty($tid)){
                $this->ts1($tid,"你有新的订单消息",$msg,$tid);
            }
        }
 
         $params = [
            "SyncOtherMachine"=>2,
            "From_Account"=>$touid,
            "To_Account" => $uid, 
            "MsgRandom" => rand(),
            "MsgBody" => [[
                "MsgType" => "TIMTextElem",
                "MsgContent" => [
                    "Text" =>  $msg
                ]
            ]]
        ];
    
        return $this->im->send('openim', 'batchsendmsg', $params);
    }
    
    
    /**
     * IM添加好友
     */
    public function getAddFriend($uid, $touid)
    {
        $params = [
            "From_Account" => config('setting.tencentIM.userPrefix') . $uid,
            "AddFriendItem" => []
        ];
        $params['AddFriendItem'][] = ["To_Account" => config('setting.tencentIM.userPrefix') . $touid, "AddSource" => "AddSource_Type_WxMini"];
        return $this->im->send('sns', 'friend_add', $params);
    }
    
    /**
     * IM好友列表
     */
    public function getFriendList($uid)
    {
        $params = [
            "From_Account" => config('setting.tencentIM.userPrefix') . $uid,
            "StartIndex" => 0
        ];
        return $this->im->send('sns', 'friend_get', $params);
    }
    
    /**
     * 创建IM群
     */
    public function createImGroup($name, $type, $uid, $gid = 0)
    {
        $params = [
            "Owner_Account" => config('setting.tencentIM.userPrefix') . $uid, // 群主id
            "Name" => $name, // 群名称（必填）
            "Type" => $type, // 群组类型：Private/Public/ChatRoom/Community(不支持AVChatRoom)（必填）
            // "MemberList" => [[
            //     "Member_Account" => config('setting.tencentIM.userPrefix') . $uid, // 成员（必填）
            //     "Role" => "Admin" // 赋予该成员的身份，目前备选项只有 Admin（选填）
            // ]], // 初始群成员列表，最多100个（选填）
            "AppDefinedData" => ['Key' => 'first_group_id', "Value" => $gid] // 群组维度的自定义字段（选填）
        ];
        
        return $this->im->send('group_open_http_svc', 'create_group', $params);
    }
    
    public function getGroupList($id)
    {
        $params = [
            "Member_Account" => config('setting.tencentIM.userPrefix') . $id,
            "GroupType" => "Public",
            "ResponseFilter" => [
                'GroupBaseInfoFilter' => [
                    'GroupId',
                    'Name',
                    'Introduction',
                    'Notification',
                    'FaceUrl',
                    'CreateTime',
                    'MemberNum'
                ],
                "SelfInfoFilter" => [
                    "Role",
                    "JoinTime",
                    "MsgSeq"
                ]
            ]
        ];
        
        return $this->im->send('group_open_http_svc', 'get_joined_group_list', $params);
    }
    
    /**
     * 获取IM群信息
     */
    public function getGroupInfo($gid)
    {
        $params = [
            "GroupIdList" => $gid
        ];
        return $this->im->send('group_open_http_svc', 'get_group_info', $params);
    }
    
    //删除够个会话
    /**
    1：表示 C2C 会话
    2：表示 G2C 会话 群聊

    */
    public function msgDel($uid,$puid,$type=1){
        /*
        {
            "From_Account":"id1",
            "Type":2,
            "To_Account":"id2",
            "ClearRamble":1
        }
        */
        $params = [
            "From_Account" => $uid, // 群主id
            "To_Account" => $puid, // 群名称（必填）
            "Type" => 1, // 群组类型：Private/Public/ChatRoom/Community(不支持AVChatRoom)（必填）
            // "MemberList" => [[
            //     "Member_Account" => config('setting.tencentIM.userPrefix') . $uid, // 成员（必填）
            //     "Role" => "Admin" // 赋予该成员的身份，目前备选项只有 Admin（选填）
            // ]], // 初始群成员列表，最多100个（选填）
            "ClearRamble" => 1
        ];
        
         return $this->im->send('recentcontact', 'delete', $params);
    }
    
    
     //屏蔽拉黑
    /**
    
    */
    public function friend_black($uid,$puid,$type=1){
 
        $params = [
            "From_Account" => $uid, // 群主id
            "To_Account" => [$puid], // 群名称（必填）
        ];
        if($type == 1){
              return $this->im->send('sns', 'black_list_add', $params);
        }else{
             return $this->im->send('sns', 'black_list_delete', $params);
        }
       
    }
    
    
    public function ts1($uid,$title,$msg,$tid){

        
       if(substr($msg,0,4) == "type"){
         
            $data = json_decode(substr($msg,4),true);
            
            $type = $data["type"];
            if($type == 0 || $type == 2 || $type == 3){
                
                $url = '/pages/find/content?id='.$data["aid"];
            }else if($type == 1){
                 $url = '/pages/find/content?id='.$data["aid"];
            }else if($type == 4){
                 $url = '/pages/user/vip';
            }else if($type == 5){
                	$url = '/task/list/my_order_dea?id='.$data["aid"].'&type=1';
                //  $url = '/task/list/my_orderlist';
            }else if($type == 6 || $type ==11){
                //  $url = '/pages/user/order';
                 $writer_uid = db("order")->where("id",$data["aid"])->value("writer_uid");
            
                 if($uid == $writer_uid){
    				$url = '/pages/my/connect?id=' .$data["aid"];
    			}else{
    				$url = '/pages/user/orderdetail?id=' .$data["aid"];
    			}
    			
            }else if($type == 7){
                
                 $writer_apply = db("writer_apply")->where(["uid"=>$uid])->order("create_time desc")->value("status");
                if($writer_apply == 0){
                    $url = "/showcase/user/writerApply?current=3";
                }else if($writer_apply == 2){
                    $url = "/pages/user/fail";
                }else{
                    $url = "/pages/user/user";
                }
               
                
            }else if($type == 8){
                
                 $url = '/pages/user/fail';
                 
            }else if($type == 9 || $type == 10){
                 $url = '/pages/user/success?id='.$data["aid"];
            }else if($type == 14){
                 $url = '/showcase/showcase/invoiceDetail?id='.$data["aid"];
            }else if($type == 15){
                
            	$url = '/showcase/showcase/showcase';
            }else if($type == 16){
                $url = '/showcase/showcase/add';
            }else if($type == 17){
              $url = '/showcase/showcase/edit?id='.$data["aid"];
            }else if($type == 19){
              $url = '/pages/user/grade?uid='.$data["aid"];
            }else if($type == 20){
              $url = '/pages/user/coin?type=2';
            }else if($type == 21){
              $url = '/pages/user/auth1';
            }else if($type == 22){
              $url = '/showcase/showcase/invoice';
            }else if($type == 23){
                
               $url = '/task/list/order_dea?id='.$data["aid"];
               
            }else if($type == 24){
              $url = '/pages/user/coin?type=1';
            }else if($type == 25){
              $url = '/pages/user/withdrawal';
            }else if($type == 26){
              $url = '/pages/user/withdrawal';
            }else if($type == 18){
              $url = $data["path"];
            }else{
                $url = "";
            }
            //"/task/list/order_dea?id=".$data["aid"]

             $saas =  send_message1($tid,$title,$data["title"],["path"=>$url]);
            return;
        }else{
             $cc = send_message1($tid,$title,$msg,["path"=>""]);
        
             return;
        }
    }
    
    public function ts($uid,$title,$msg){

        
       if(substr($msg,0,4) == "type"){
         
            $data = json_decode(substr($msg,4),true);
            
            $type = $data["type"];
            if($type == 0 || $type == 2 || $type == 3){
                
                $url = '/pages/find/content?id='.$data["aid"];
            }else if($type == 1){
                 $url = '/pages/find/content?id='.$data["aid"];
            }else if($type == 4){
                 $url = '/pages/user/vip';
            }else if($type == 5){
                	$url = '/task/list/my_order_dea?id='.$data["aid"].'&type=1';
            }else if($type == 6 || $type == 11){
                //  $url = '/pages/user/order';
                 $writer_uid = db("order")->where("id",$data["aid"])->value("writer_uid");
           
                 if($uid == $writer_uid){
    				$url = '/pages/my/connect?id=' .$data["aid"];
    			}else{
    				$url = '/pages/user/orderdetail?id=' .$data["aid"];
    			}
			
            }else if($type == 7){
                
                //  $writer_apply = db("writer_apply")->where(["uid"=>$uid])->order("create_time desc")->value("status");
                // if($writer_apply == 0){
                //     $url = "/showcase/user/writerApply?current=3";
                // }else if($writer_apply == 2){
                //     $url = "/pages/user/fail";
                // }else{
                     $url = "/showcase/user/writer-center";
             
               
                
            }else if($type == 8){
                
                 $url = '/pages/user/fail';
                 
                
            }else if($type == 9 || $type == 10){
                 $url = '/pages/user/success?id='.$data["aid"];
            }else if($type == 14){
                 $url = '/showcase/showcase/invoiceDetail?id='.$data["aid"];
            }else if($type == 15){
                
            	$url = '/showcase/showcase/showcase';
            }else if($type == 16){
                $url = '/showcase/showcase/add';
            }else if($type == 17){
              $url = '/showcase/showcase/edit?id='.$data["aid"];
            }else if($type == 19){
              $url = '/pages/user/grade?uid='.$data["aid"];
            }else if($type == 20){
              $url = '/pages/user/coin?type=2';
            }else if($type == 21){
              $url = '/pages/user/auth1';
            }else if($type == 22){
              $url = '/showcase/showcase/invoice';
            }else if($type == 24){
              $url = '/pages/user/coin?type=1';
            }else if($type == 25){
              $url = '/pages/user/withdrawal';
            }else if($type == 26){
              $url = '/pages/user/withdrawal';
            }else if($type == 18){
              $url = $data["path"];
            }else{
                $url = "";
            }
           
             $saas =  send_message($uid,$title,$data["title"],["path"=>$url]);
            return;
        }else{
             $cc = send_message($uid,$title,$msg,["path"=>""]);
        
             return;
        }
    }
    
}
